package spring.boot.redis.service.impl;

import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import spring.boot.redis.config.RedissonManager;
import spring.boot.redis.service.RedissonService;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class RedissonServiceImpl implements RedissonService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    RedissonManager redissonManager;

    @Override
    public Boolean set(String key, String value) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key,value);
        return true;
    }

    @Override
    public Boolean set(String key, String value, long timeout, TimeUnit timeUnit) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key,value,timeout,timeUnit);
        return true;
    }

    @Override
    public String get(String key) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object obj = valueOperations.get(key);
        if (obj != null){
            return obj.toString();
        }
        return null;
    }

    @Override
    public RLock getReentrantLock(String key) {
        try {
            return redissonManager.redisson().getLock(key);
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public RLock fairLock(String key) {
        try {
            return redissonManager.redisson().getFairLock(key);
        } catch (IOException e) {
            return null;
        }
    }

    @Override
    public RReadWriteLock rwlock (String key) {
        try {
            return redissonManager.redisson().getReadWriteLock(key);
        } catch (IOException e) {
            return null;
        }
    }


}
